package org.jeecg.demo.wx.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.demo.wx.config.COSConfig;
import org.jeecg.demo.wx.constant.FileExtensionConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * 功能描述
 * 腾讯cos对象存储工具类
 *
 * @author: zgq
 * @date: 2024年02月01日 16:05
 */
@Component
public class COSUtil {

    @Autowired
    private COSConfig cosConfig;

    public COSClient init() {
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        Region region = new Region(cosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }

    public Result<String> uploadFile(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException("文件名不能为空");
        }
        String fileType = checkFileType(originalFilename, FileExtensionConstant.JPG, FileExtensionConstant.PNG);
        String buckerName = cosConfig.getBuckerName();
        String key = FilePathUtils.getFileKey(fileType);
        COSClient cosClient = init();
        try {
            cosClient.putObject(new PutObjectRequest(buckerName, key, file.getInputStream(), null));
            return Result.ok(cosConfig.getUrl() + "/" + key);
        } catch (CosClientException e) {
            throw new RuntimeException(e);
        } finally {
            cosClient.shutdown();
        }
    }

    private String checkFileType(String originalFilename, String... expectFileType) {
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        for (String type : expectFileType) {
            if (Objects.equals(fileType, type)) {
                return type;
            }
        }
        throw new RuntimeException("请上传" + Arrays.toString(expectFileType) + "类型的文件");
    }
}
